package cmd

import (
	"io/ioutil"

	log "github.com/sirupsen/logrus"

	"gitee.com/minph/siphan/core"
	"gitee.com/minph/siphan/diycode"
	"gitee.com/minph/siphan/fs"
	"github.com/urfave/cli/v2"
)

func encodeWork(file, content string, codeSlice diycode.CodeSlice) error {

	ecres, err := core.EncryptFromSlice(content, codeSlice)
	if err != nil {
		return wrap(err)
	}

	baseName := fs.RemoveFileExt(file)
	encryptFile := baseName + ".siphan"

	err = fs.ClearFile(encryptFile)
	if err != nil {
		return wrap(err)
	}

	ecresValhexKey, err := codeSlice.GenInputHexData(ecres.Val)
	if err != nil {
		return wrap(err)
	}

	err = fs.WriteNewFile(encryptFile, ecresValhexKey.PrintStringText())
	if err != nil {
		return wrap(err)
	}

	hexKey, err := codeSlice.GenHexKey()
	if err != nil {
		return wrap(err)
	}

	keyFile := baseName + ".siphan.key"

	err = fs.ClearFile(keyFile)
	if err != nil {
		return wrap(err)
	}

	err = fs.WriteNewFile(keyFile, hexKey.PrintStringText())
	if err != nil {
		return wrap(err)
	}

	log.Info("encrypt file successfully")
	log.Infof("encrypt file [%v]\n", encryptFile)
	log.Infof("decrypt key file [%v]\n", keyFile)

	return nil
}

func EncodeHandler(c *cli.Context) error {
	key := c.String("key")
	file := c.String("file")
	codeSlice, _ := diycode.GetRandCodeSlice()

	if len(key) > 0 {
		log.Infof("Encrypt with key [%v]\n", key)
		codeSliceFromFile, err := fs.ReadHexKeyFromFile(key)
		if err != nil {
			log.Errorf("Invalid key content in [%v]\n", key)
			return wrap(err)
		}
		codeSlice = codeSliceFromFile
	} else {
		log.Info("Encrypt with default inner key")
	}

	content, err := ioutil.ReadFile(file)
	if err != nil {
		log.Errorf("Can not read data of [%v]\n", file)
		return wrap(err)
	}

	return encodeWork(file, string(content), codeSlice)

}
